#include "qvolumeanalyzer.h"
#include <math.h>
#include <QDebug>

QVolumeAnalyzer::QVolumeAnalyzer(const QAudioFormat &format, QObject *parent) :
    QIODevice(parent)
    ,m_format(format)
    ,threshold(50)
    ,exceeded(0)
{
}

/**
   * Called when data is obtained. Stores each m_stepSize sample
   * into a QList to be analysed.
   */
qint64 QVolumeAnalyzer::writeData(const char *data, qint64 maxlen)
{
    // RMS Method
    QByteArray buffer(data);
    double rms   = 0;
    ushort byte1 = 0;
    ushort byte2 = 0;
    short value  = 0;
    int volume   = 0;

    rms = (short)(byte1 | (byte2 << 8));

    for (int i = 0; i < buffer.length() - 1; i += 2)
    {
        byte1 = data[i];
        byte2 = data[i + 1];

        value = (short)(byte1 | (byte2 << 8));
        rms += pow((double)value, 2);
    }
    rms /= (double)(buffer.length() / 2);
    volume = (int)floor(sqrt(rms));

    if( (volume > threshold) )
    {
        ++exceeded;
        emit thresholdExceeded(volume);
        qDebug() << "time: ["<< QString::number(exceeded) << "] buffer.length " + QString::number(buffer.length()) + " Volume:" + QString::number(volume);
    } else {
        //if( exceeded >= 1 && exceeded < 2 ){
        if( exceeded == 1 &&
            ( volume > 3000 && volume < 4000)
          ){
            emit clap();
        }
        exceeded = 0;
    }
    return maxlen;
}

/**
* Opens the parent QIODevice. Sets up the analysation parameters.
*/
void QVolumeAnalyzer::start()
{
    open(QIODevice::WriteOnly);
}

/**
* Closes the parent QIODevice, thus the voice is not analysed anymore.
* Resets the m_samples QList.
*/
 void QVolumeAnalyzer::stop()
 {
     close();
 }

/**
* Empty implementation for readData, since no data is provided
* by the VoiceAnalyzer class.
*/
qint64 QVolumeAnalyzer::readData(char *data, qint64 maxlen)
{
    Q_UNUSED(data);
    Q_UNUSED(maxlen);

    return 0;
}
